<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>音频可视化</title>
    <style>
        /* 样式可以根据自己的喜好进行调整 */
        body {
            background-color: #333;
            color: #FFF;
            font-family: Arial, sans-serif;
            text-align: center;
        }

        h1 {
            margin-top: 50px;
            font-size: 36px;
            font-weight: normal;
            margin-bottom: 50px;
        }

        #audio-player {
            margin-bottom: 50px;
        }

        canvas {
            display: block;
            margin: 0 auto;
            background-color: #000;
        }
    </style>
</head>
<body>
<h1>音频可视化</h1>

<audio id="audio-player" controls>
    <source src="test.mp3" type="audio/mpeg">
    Your browser does not support the audio element.
</audio>

<canvas id="canvas"></canvas>

<script>
    // 获取canvas元素
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext("2d");

    // 设置canvas宽度和高度
    canvas.width = window.innerWidth * 0.8;
    canvas.height = window.innerHeight * 0.6;

    // 创建音频上下文
    const audioCtx = new AudioContext();

    // 创建媒体源
    const source = audioCtx.createMediaElementSource(document.getElementById("audio-player"));

    // 创建分析器
    const analyser = audioCtx.createAnalyser();

    // 将媒体源和分析器连接
    source.connect(analyser);

    // 将分析器连接到音频上下文的目标（扬声器）
    analyser.connect(audioCtx.destination);

    // 设置分析器参数
    analyser.fftSize = 256;
    const bufferLength = analyser.frequencyBinCount;
    const dataArray = new Uint8Array(bufferLength);

    // 绘制函数
    function draw() {
        // 获取数据
        analyser.getByteFrequencyData(dataArray);

        // 清空画布
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        // 绘制频谱图
        const barWidth = (canvas.width / bufferLength) * 2.5;
        let barHeight;
        let x = 0;

        for (let i = 0; i < bufferLength; i++) {
            barHeight = dataArray[i];

            ctx.fillStyle = "rgb(" + (barHeight + 100) + ",50,50)";
            ctx.fillRect(x, canvas.height - barHeight / 2, barWidth, barHeight / 2);

            x += barWidth + 1;
        }

        // 递归调用绘制函数
        requestAnimationFrame(draw);
    }

    // 开始绘制
    draw();
</script>
</body>
</html>
